package com.woniu.filter;

import com.woniu.outlet.dao.WorkerPoMapper;
import com.woniu.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private WorkerPoMapper workerPoMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获得客户端请求的头信息
        String tokenStr = request.getHeader("tokenStr");
        String path = request.getRequestURI().toString();

        if (path.contains("doc.html") || path.contains(".js") || path.contains(".css")
                || path.contains("swagger-resources") || path.contains("api-docs")
                || path.contains("v2") || path.contains("favicon.ico") || path.contains("login")) {
            filterChain.doFilter(request, response);

            return;
        }

        //获取token中的用户名
        String username = JwtTokenUtil.getUserId(tokenStr);
        //根据用户名查询数据库的权限标识符信息
        List<String> percodes = workerPoMapper.getPercodeByUsername(username);
        List<GrantedAuthority> authorities = new ArrayList<>();
        percodes.forEach(percode -> {
            authorities.add(new SimpleGrantedAuthority(percode));
        });


        Authentication authentication =
                new UsernamePasswordAuthenticationToken(username, "", authorities);

        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);

    }
}
